#!/usr/bin/env python
#-*- coding:utf-8 -*-
#Kontrolcu Main

from optparse import OptionParser, OptionGroup
from constants import *

import os
import sys
import hashlib
import gettext

#For using unicode utf-8

reload(sys).setdefaultencoding("utf-8")

#For developing without setup
MODULEPATH = os.getcwd()[:-3] + "qt4"
sys.path.append(MODULEPATH)

from dialogfromcli import *
try:
    from libkontrolcu import *
    if getlibversion() != "2.0":
        print _("Warning: Your libkontrolcu version is not 2.0!")
        print _("Your libkontrolcu version is") + " " + getlibversion()
        print _("So kontrolcu may not work succesfully.")
except ImportError:
    print _("Fatal Error:\nlibkontrolcu module is not found!")
    sys.exit(1)
except NameError:
    print _("Fatal Error:\nYou are using an old version of libkontrolcu.\nPlease remove old libkontrolcu.")
    sys.exit(1)

#For multilanguage support
gettext.install("kontrolcu", unicode=1)

def MainMenu():
    Menu=OptionParser(usage="kontrolcu [options] [files]",
                description=_("Kontrolcu is a checking tool which you can check file summaries and writing them to a checksum file or read a checksum file."),
                    version=_("Version: %s")% VERSION)
    Menu.add_option("-t", "--type", dest="Type", help=_("Check summary type: md5,sha1,sha224,sha256,sha384,sha512"))
    Menu.add_option("-s", "--save", dest="Save", action="store_true", help=_("Saving check summary to a file"))
    Menu.add_option("-c", "--compare", dest="Summary", help=_("Compare check summary with file's check summary"))
    Menu.add_option("-f", "--filecont", dest="ContFile", help=_("Use check summary file for checking"))

    Group=OptionGroup(Menu, _("Other Parameters"))
    Group.add_option("-g", "--withgui", dest="Gui", action="store_true", help=_("Use Qt4 interface"))
    Group.add_option("-d", "--dialog", dest="Dialog", action="store_true", help=_("Return output on Qt4 dialog window"))
    Menu.add_option_group(Group)

    (Options, Files) = Menu.parse_args()

    if Options.Gui:
        gui = UsingQt()
        gui.GuiQt()

    elif Options.Dialog:
        if Options.Summary:
            from PyQt4.QtGui import QApplication
            app = QApplication(sys.argv)
            dialog = PiFromCli(FileList=Files)
            dialog.CompareSummary(Options.Summary)
        elif Options.ContFile:
            from PyQt4.QtGui import QApplication
            app = QApplication(sys.argv)
            dialog = PiFromCli()
            dialog.CompareFromFile(Options.ContFile)
        elif Options.Type:
            from PyQt4.QtGui import QApplication
            app = QApplication(sys.argv)
            dialog = PiFromCli(ControlType=Options.Type, FileList=Files)
            dialog.ControlFiles()
        else:
            Menu.error(_("Type is not exist"))
    elif Options.Summary:
        CompareCli(Files[0], Options.Summary)

    elif Options.ContFile:
        ContFromFile(Options.ContFile)

    elif Options.Type:
        Check(Options.Type, Files, Options.Save)

    else:
        Menu.error(_("Type is not exist"))

def CompareCli(File, Value):
    Object=CUnit(File, Value)
    Object.Compare()
    if Object.CompValue:
        print makeGreen(text=_("%s is OK")% Object.Name)
    else:
        print makeRed(text=_("%s is Wrong")% Object.Name)

def Check(Type, Files, Save):
    Controls = { "md5" : hashlib.md5,
                "sha1" : hashlib.sha1,
              "sha224" : hashlib.sha224,
              "sha256" : hashlib.sha256,
              "sha384" : hashlib.sha384,
              "sha512" : hashlib.sha512 }
    ConType=Controls.get(Type)
    Extension="." + Type + "sum"
    result=[]
    tour=0

    for i in Files:
        if os.path.isdir(i):
            continue
        tour+=1
        Object=CUnit(i)
        Object.CheckSum(ConType)
        if Save:
            if len(Files) == 1:
                SavingFileName = Object.Name + Extension
            elif tour == 1:
                SavingFileName = raw_input(_("Please insert saving file name: ")) + Extension
        if Object.ValueReal:
            Out = Object.ValueReal + "  " + Object.Name
            if Save:
                try:
                    if tour == 1:
                        SavingFile = open(SavingFileName, "w")
                    else:
                        SavingFile = open(SavingFileName, "a")
                    SavingFile.write(Out)
                    SavingFile.write("\n")
                    SavingFile.close()
                except IOError, (ErrNo,Error):
                    if ErrNo == 13:
                        print makeRed(text=_("File is not saving."))
            else:
                result.append(Out)
    if not Save:
        for i in result:
            print i

def ContFromFile(File):
    if File[:5] == "http:" or File[:4] == "ftp:" or File[:6] == "https:":
        path = raw_input(_("Enter the location of files (Here is ./): "))
        Output = FromFileCheck(File, path)
    else:
        Output = FromFileCheck(File)

    for i in Output.keys():
        if Output[i] == "0":
            print makeBlue(text=_("%s is Missing")% i)
        elif Output[i] == "+":
            print makeGreen(text=_("%s is OK")% i)
        elif Output[i] == "-":
            print makeRed(text=_("%s is Wrong")% i)

class UsingQt:
    def __init__(self, message={}):
        self.Message = message
    def GuiQt(self):
        try:
            from PyQt4.QtGui import QApplication
            import mainqt
            app = QApplication(sys.argv)
            form = mainqt.MainQt()
            form.show()
            app.exec_()
        except ImportError:
            print _("Fatal Error:\nGui is not found!")
    def OpenDialog(self):
        try:
            from PyQt4.QtGui import QApplication
            from dialogs import TextDialog
            app = QApplication(sys.argv)
            form = TextDialog(message=self.Message)
            form.show()
            app.exec_()
        except ImportError:
            print _("Error:\nDialog module is not found!")

#if __name__ == "__main__":
#    MainMenu()
